<?php

namespace app\admin\model;

use app\common\model\TimeModel;
use think\Exception;
use think\Model;

class ShopCate extends TimeModel
{

    protected $name = "shop_cate";
    protected $deleteTime = 'delete_time';


    public function stores()
    {
        return $this->hasMany('app\admin\model\ShopStore', 'cate_id', 'id');
    }

    public static function onBeforeWrite(Model $model)
    {
        if ($model->pid > 0) {
            throw new Exception('店铺暂不支持多级分类');
        }
    }

    public static function onAfterWrite()
    {
        cache('shop_cate_menu', null);
    }

    public static function onAfterDelete()
    {
        cache('shop_cate_menu', null);
    }

    /**
     * @title 获取分类树
     * @param int $pid
     * @return array|\Closure|mixed|object|\think\App
     * @author FashionJune
     */
    public function getCateList(int $pid = 0)
    {
        try {
            if (cache('?shop_cate_menu')) {
                return cache('shop_cate_menu');
            } else {
                $cate_array = $this->where('pid', $pid)->field(['id', 'pid', 'title'])->order('sort','desc')->select()->toArray();
                //获取树形结构
                $tree = array2tree($cate_array, $pid, 'pid', 'id');
                //获取树形排序处理后的数组
                $list = tree2array($tree);
                foreach ($list as &$vo) {//用制表符├显示层级关系
                    $repeatString = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    $markString = str_repeat("{$repeatString}├{$repeatString}", $vo['deep'] - 1);
                    $vo['title'] = $markString . $vo['title'];
                }
                $top[] = ['id' => 0, 'pid' => 0, 'title' => '顶级分类'];
                $return = array_merge($top, $list);
                cache('shop_cate_menu', $return);
                return $return;
            }
        } catch (\Exception $e) {
            return error('获取分类树失败');
        }

    }


}